package com.zjuee.web.basic.captcha.controller;

import com.zjuee.base.bean.response.R;
import com.zjuee.base.constant.Common;
import com.zjuee.core.translation.utils.SpringContextUtil;
import com.zjuee.service.basic.captcha.service.CaptchaService;
import com.zjuee.service.basic.captcha.vo.CaptchaVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 验证码 web 接口
 *
 * @author wu liang
 * @since 1.0
 */
@Slf4j
@RestController
@RequestMapping(path = Common.Service.ZJUEE_BASIC_CAPTCHA_URL_PREFIX, name = Common.Service.ZJUEE_BASIC_SERVICE_NAME)
public class CaptchaController {

    @Resource
    private SpringContextUtil springContextUtil;

    /**
     * 获取验证码
     *
     * @param type String
     * @return CaptchaVo
     */
    @GetMapping("/get")
    public R<CaptchaVo> getCaptcha(@RequestParam("type") String type) {
        try {

            if ("slide".equals(type) || "clickWord".equals(type)) {
                CaptchaService instance = (CaptchaService) springContextUtil.getBean(type);
                CaptchaVo captchaVo = instance.get();
                if (null != captchaVo) {
                    return R.ok(captchaVo);
                }
            }
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.fail();
    }

    /**
     * 校验验证码
     *
     * @param captchaVo CaptchaVo
     * @return String
     */
    @PostMapping("/check")
    public R<String> checkCaptcha(@RequestBody CaptchaVo captchaVo) {
        if ("slide".equals(captchaVo.getType()) || "clickWord".equals(captchaVo.getType())) {

            CaptchaService instance = (CaptchaService) springContextUtil.getBean(captchaVo.getType());
            String captchaToken = instance.check(captchaVo);
//            RedisUtil.expire(MySessionDAO.PREFIX + header, 3600);
            return R.ok(captchaToken);
        }
        return R.fail();
    }

    /**
     * 获取短信验证码
     *
     * @param mobile String
     * @return Boolean
     */
    @GetMapping("/phone/captcha")
    public R<Boolean> getPhoneCaptcha(@RequestParam("mobile") String mobile) {
        try {
            CaptchaService instance = (CaptchaService) springContextUtil.getBean("phone");
            Boolean boo = instance.get(mobile);
            return R.ok(boo);
        } catch (Exception e) {
            e.getStackTrace();
            return R.fail(e.getMessage());
        }
    }
}
